

/// <reference path="./../Define.ts" />
/// <reference path="./../module/ModuleMgr.ts" />
/// <reference path="./../module/BaseModule.ts" />

/// <reference path="./define/ConfigDefine.ts" />
/// <reference path="./../configs.ts" />

namespace apeng {

    @moduleMgr.add(EModuleType.config)
    export class ConfigModule extends BaseModule {
        /**数组形式的配置数据 */
        public readonly arr: { [Key in keyof TConfigFileName]: TConfigFileName[Key][] } = <any>{}
        /**对象形式的配置数据 */
        public readonly obj: { [Key in keyof TConfigFileName]: { [id: number]: TConfigFileName[Key] } } = <any>{}

        onInstance() {

            let objs = this.deParse(configs)
            // 解析配置表
            for (let configName in ConfigFileName) {
                let obj: any = objs[configName]
                this.arr[configName] = []
                if (configName.indexOf("language") != -1) {
                    for (let key in obj)
                        this.arr[configName].push(obj[key])
                }
                else {
                    for (let key in obj) {
                        obj[key].id = Number(key)
                        obj[key].configName = configName
                        this.arr[configName].push(obj[key])

                        let parseKey = (ConfigFileName as any)[configName]
                        if (parseKey !== null!)
                            obj[key] = (obj[key] as any)[parseKey]
                    }
                }
                this.obj[configName] = obj
            }
        }

        // 解压缩
        private deParse(sources: any) {
            let obj: any = {}
            for (let key in sources) {
                let value: any = null!
                if (key.indexOf("language") != -1) {
                    value = sources[key][1]
                    for (let _k in value) {
                        for (let i = 0; i < value[_k].length; i++) {
                            let v = value[_k][i]
                            if (v && typeof v == "string")
                                value[_k][i] = v.split("\\n").join("\n")
                            else
                                value[_k][i] = v + ""
                        }
                    }
                }
                else {
                    value = {}
                    let k = []
                    for (let _k of sources[key][0])
                        k.push(_k)
                    let v = sources[key][1]
                    for (let _k in v) {
                        value[_k] = {}
                        for (let i = 0; i < k.length; i++)
                            value[_k][k[i]] = v[_k][i]
                    }
                }
                obj[key] = value
            }
            return obj
        }
    }
}